import dayjs from "dayjs";
import { type PaginationProps } from "@pureadmin/table";
import { AddPushTask, PushTaskList, GetPushTaskBaseData } from "@/api/stu/bankBigData";
import { useRoute } from "vue-router";
import { ElMessage, FormInstance } from "element-plus";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
export function useCreditReport() {
  const route = useRoute();
  const dataList = ref<any>([]); //接口原数据
  //新建时候选择器的数据
  const productTypeList = ref()
  const pushMethodList = ref()
  const pushFrequencyList = ref()
  const startMethod = ref()
  const customerList = ref()
  const formData = reactive({
    ProductType: "",
    PushMethod: "",
    PushFrequency: "",
    StartMethod: "",
    PushTaskName: "",
    UserPortraitId: "",
    startTime: ""
  })
  const taskTittleRegex = /^[\u4e00-\u9fa5]{5,20}$/;// 校验中文
  const addProVisible = ref<boolean>(false); //新建弹窗

  const loading = ref<boolean>(false);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 30,
    currentPage: 1,
    pageSizes: [5, 10, 30],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "推送任务名称",
      prop: "pushTaskName",
      minWidth: 200
    },
    {
      label: "产品类型",
      prop: "productType",
      minWidth: 300
    },
    {
      label: "客户群",
      prop: "customerGroupName",
      minWidth: 300
    },
    {
      label: "推送方式",
      prop: "pushMethod",
      minWidth: 300
    },
    {
      label: "推送结果",
      prop: "pushStatus",
      minWidth: 300
    },
  ];

  const rule = {
    PushTaskName: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (taskTittleRegex.test(formData.PushTaskName) === false) {
            return callback(new Error('任务名称应该请输5 - 20个汉字'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    ProductType: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: '请选择产品类型',
      }
    ],
    UserPortraitId: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: '请选择客户群',

      }
    ],
    PushMethod: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: '请选择推送方式',

      }
    ],
    StartMethod: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: '请选择推送时间',

      }
    ],
  }



  //获取列表数据
  async function getList() {
    const respone = await PushTaskList({
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      taskId: route.query.taskId,
      planId: route.query.planId,
    });
    if (respone.success) {
      pagination.total = respone?.data.totalCount;
      dataList.value = respone?.data.items;
    } else {
      ElMessage.error(respone.msg);
    }
  }

  function handleCurrentChange() {
    getList()
  }
  function handleSizeChange() {
    getList()
  }

  async function save(shareFrom: FormInstance | undefined) {
    (shareFrom as any).validate(async valid => {
      if (!valid) return;
      if (taskTittleRegex.test(formData.PushTaskName) === false) {
        ElMessage.warning('任务名称应该请输5 - 20个汉字')
        return
      }
      const params = {
        taskId: route.query.taskId,
        planId: route.query.planId,
        ProductType: formData.ProductType,
        PushMethod: formData.PushMethod,
        PushFrequency: formData.PushFrequency,
        StartMethod: formData.StartMethod,
        PushTaskName: formData.PushTaskName,
        UserPortraitId: formData.UserPortraitId,
        startTime: formData.startTime,
        studentAnswer: JSON.stringify(formData)
      }

      let res = await AddPushTask(params)
      if (res.status == 200) {
        ElMessage.success(res.msg);
        addProVisible.value = false
        for (let variable in formData) {
          formData[variable] = '';
        }
        getList()
      } else {
        ElMessage.error(res.msg);
      }
    })
  }
  function cancel() {
    addProVisible.value = false
    for (let variable in formData) {
      formData[variable] = '';
    }
    getList()
  }

  onMounted(async () => {
    let res = await GetPushTaskBaseData({
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    if (res.success) {
      productTypeList.value = res?.data.filter(item => item.name == 'ProductType')[0].selectOptions
      pushMethodList.value = res?.data.filter(item => item.name == 'PushMethod')[0].selectOptions
      pushFrequencyList.value = res?.data.filter(item => item.name == 'PushFrequency')[0].selectOptions
      startMethod.value = res?.data.filter(item => item.name == 'StartMethod')[0].selectOptions
      customerList.value = res?.data.filter(item => item.name == '客户群')[0].selectOptions
    } else {
      ElMessage.error(res.msg);
    }
    getList()
  })

  return {
    dataList,
    loading,
    pagination,
    columns,
    productTypeList,
    pushMethodList,
    pushFrequencyList,
    startMethod,
    customerList,
    formData,
    addProVisible,
    handleCurrentChange,
    handleSizeChange,
    save,
    cancel,
    rule
  }
}
